package dynamicService

import (
	"fmt"
	"hotter/model"
	"io/ioutil"
	"log"
	"os"
	"sync"
)

type DynamicService struct {
}

func NewDynamicService() *DynamicService {
	return &DynamicService{}
}

func (ds *DynamicService) ReadFileDetail(folder string) string {
	f, err := os.Open(folder)
	if err != nil {
		fmt.Println("read file fail", err)
		return "读取失败"
	}
	defer f.Close()

	fd, err := ioutil.ReadAll(f)
	if err != nil {
		fmt.Println("read to fd fail", err)
		return "读取字节失败"
	}

	return string(fd)
}

func (ds *DynamicService) GetFileInfo(folder string) *model.FileInfo {
	fileInfo, err := os.Stat(folder)
	if os.IsNotExist(err) {
		fmt.Println("file not exist")
	}

	return &model.FileInfo{
		Name:        fileInfo.Name(),
		IsDir:       fileInfo.IsDir(),
		ModTime:     fileInfo.ModTime(),
		Size:        fileInfo.Size(),
		SubFileInfo: []*model.FileInfo{},
	}
}

func (ds *DynamicService) GetFilesByLevel(folder string) interface{} {
	f := ds.GetFileInfo(folder)
	if f.IsDir {
		var file_list []*model.FileInfo
		files, _ := ioutil.ReadDir(folder)
		for _, file := range files {
			fi := ds.GetFileInfo(folder + "/" + file.Name())
			file_list = append(file_list, fi)
		}
		return file_list
	} else {
		f.Details = ds.ReadFileDetail(folder)
	}

	return f.Details
}

func (ds *DynamicService) GetFilesByLevelAsync(folder string) interface{} {
	f := ds.GetFileInfo(folder)
	if f.IsDir {
		var file_list []*model.FileInfo
		files, _ := ioutil.ReadDir(folder)
		var wg sync.WaitGroup
		for _, file := range files {
			file := file
			wg.Add(1)
			go func(wg *sync.WaitGroup) {
				defer func() {
					err := recover()
					if err != nil {
						log.Println("range level files error：", err)
						return
					}
				}()

				fi := ds.GetFileInfo(folder + "/" + file.Name())
				file_list = append(file_list, fi)
				wg.Done()
			}(&wg)
		}
		wg.Wait()
		return file_list
	} else {
		f.Details = ds.ReadFileDetail(folder)
	}

	return f.Details
}
